import initSqlJs from '@jlongster/sql.js';
import {SQLiteFS} from 'absurd-sql';
import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend';

async function run() {
    let SQL = await initSqlJs({locateFile: file => `/node_modules/@jlongster/sql.js/dist/${file}`});
    let sqlFS = new SQLiteFS(SQL.FS, new IndexedDBBackend());
    SQL.register_for_idb(sqlFS);

    SQL.FS.mkdir('/sql');
    SQL.FS.mount(sqlFS, {}, '/sql');

    const path = '/sql/db.sqlite';
    if (typeof SharedArrayBuffer === 'undefined') {
        let stream = SQL.FS.open(path, 'a+');
        await stream.node.contents.readIfFallback();
        SQL.FS.close(stream);
    }

    let db = new SQL.Database(path, {filename: true});



    // You might want to try `PRAGMA page_size=8192;` too!
    db.exec(`
    PRAGMA page_size = 8192;
    PRAGMA journal_mode = MEMORY;
    VACUUM;
`);
        const res = db.exec('SELECT * FROM telemetry');
    console.timeEnd('SQL Finish');
    console.log(res);
    return


    // 创建data表
    db.exec(`
        CREATE TABLE IF NOT EXISTS telemetry
        (
            id         INTEGER PRIMARY KEY,
            timestamp  INTEGER NOT NULL,
            sourceCode TEXT    NOT NULL,
            parsedData Text    NOT NULL
        );
    `);


    // 模拟插入数据
    const insertData = (id, timestamp, sourceCode, parsedData) => {
        try {

            let stmt = db.prepare("INSERT INTO telemetry (timestamp, sourceCode, parsedData) VALUES (?, ?, ?)");
            stmt.run([timestamp, sourceCode, parsedData]);
            stmt.free(); // 使用后立即释放资源
        } catch (error) {

            // Wrong API use : tried to bind a value of an unknown type (undefined).
            console.error("插入数据时出错:", error);
            throw error;
        }
    };

    // 生成随机数据
    const generateRandomData = () => {
        const labels = ["label1", "label2", "label3", "label4", "label5"];
        const parsedData = [];
        for (let i = 0; i < 300; i++) {
            parsedData.push({
                label: labels[Math.floor(Math.random() * labels.length)],
                raw: Math.floor(Math.random() * 1000),
                sourceCode: "0xff21931290",
                value: Math.random().toFixed(4),
                bit_length: Math.floor(Math.random() * 32)
            });
        }
        return parsedData;
    };

    db.exec("BEGIN TRANSACTION");
    // 执行插入操作 10 万条数据
    for (let i = 0; i < 10000; i++) {
        const timestamp = Date.now() - Math.floor(Math.random() * 1000000); // 随机时间戳，确保 timestamp 是有效的
        const sourceCode = "EB9044220153D000000000000000000000000000000000000000000000000000000000000000D0CC0000000017F7ECF30107660000000000006262200000005B00005B005B000000D100F2FE0760F65DFA4004F2F6710000000017F7EC0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000015000000CC007A00200043FFF200000017F7EC00000000000000FF78000E00000000000000000000000000000000000000000000000000000000000000000000000062626262626262626062626261626161626161C06200000063000050000000000000000000100900980006480648064806480A5A0A5A0A5A0648064806480768076806480648000000000000000000000000000000000000000000000000000000000011000000013F8000003F800000F000002DF62DF60000000000000000004909D7"; // 固定sourceCode
        const parsedData = JSON.stringify(generateRandomData()); // 生成随机的parsedData
        insertData(i, timestamp, sourceCode, parsedData); // 插入数据
    }
    db.exec("COMMIT");
    console.log("插入完成")
    console.time('SQL Finish');
    const res = db.exec('SELECT * FROM telemetry');
    console.timeEnd('SQL Finish');
    console.log(res);


}

/**
 * 我的数据结构
 * {
 *     id:1,
 *     timestamp: 时间戳,
 *     sourceCode: "eb90-09d7" 字符串,
 *     parsedData: [{}, ...] 大概300个左右对象, 每个对象的结构{label: xx, raw:xx, sourceCode:xx, value:xx, bit_length:xx
 * }
 * }
 */
await run()